package org.example.shop.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.shop.entity.User;
import org.example.shop.service.UserService;
import org.example.shop.util.CaptchaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/register")
    public String register() {
        return "register";
    }

    @PostMapping("/register")
    public String handleRegister(
            @RequestParam String account,
            @RequestParam String password,
            @RequestParam String email,
            @RequestParam String telphone,
            @RequestParam String captcha,
            HttpServletRequest request
    ) {
        // 从Session中获取验证码
        String sessionCaptcha = (String) request.getSession().getAttribute("captcha");
        if (sessionCaptcha == null || !sessionCaptcha.equalsIgnoreCase(captcha)) {
            return "redirect:/user/register?error=captcha_error";
        }

        // 检查用户名是否已存在
        if (userService.isAccountExists(account)) {
            return "redirect:/user/register?error=account_exists";
        }

        // 调用UserService插入用户
        boolean re = userService.insertUser(account, password, email, telphone);
        return re ? "redirect:/user/login" : "redirect:/user/register";
    }

    @PostMapping("/login")
    public String handleLogin(
            @RequestParam String account,
            @RequestParam String password,
            HttpServletRequest request,
            Model model) {
        User user = userService.validateUser(account, password);
        if (user == null) {
            model.addAttribute("msg", "账号或密码错误");
            return "login";
        }

        // 登录成功，将用户信息存入session
        request.getSession().setAttribute("loginUser", user);
        return "redirect:/";
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        // 清除Session
        request.getSession().invalidate();

        // 设置响应头禁止缓存
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
        response.setHeader("Pragma", "no-cache"); // HTTP 1.0
        response.setDateHeader("Expires", 0); // Proxies

        return "redirect:/";
    }

    @GetMapping("/captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 生成验证码文本
        String captchaText = CaptchaUtils.generateCaptchaText(4);

        // 将验证码存入Session
        request.getSession().setAttribute("captcha", captchaText);

        // 生成图片并返回
        response.setContentType("image/png");
        byte[] imageBytes = CaptchaUtils.generateCaptchaImage(captchaText);
        response.getOutputStream().write(imageBytes);
        response.getOutputStream().flush();
    }
}